<template>
  <div>
    <headNav :title="operationName" ></headNav>
    <!-- 亲属添加修改模块 -->
    <div v-if="operationName == '添加家长' || operationName == '编辑家长'" >
      <div class="bigDivCss" >
        <span>家长姓名：</span>
        <input type="text" v-model="relative.name" placeholder="请输入家长姓名" />
      </div>
      <div class="bigDivCss" >
        <span>家长电话：</span>
        <input type="number" maxlength="10" v-model="relative.phone" placeholder="请输入家长电话" />
      </div>

      <div class="bigDivCss" >
        <span>亲属关系：</span>
        <button @click="show1 = true" class="buttonCss" >选择</button>
      </div>
      <!-- 选择亲属关系弹窗 -->
      <popup v-model="show1">
        <popup-header
        :left-text="'取消'"
        :right-text="'确定'"
        :title="'请选择亲属关系'"
        :show-bottom-border="false"
        @on-click-left="show1 = false"
        @on-click-right="determineClick()"></popup-header>
        <group gutter="0" >
          <radio :options="enumeration" :value="relative.relationCode" @on-change="enumerationChange" ></radio>
        </group>
      </popup>

    </div>
    <!-- 头像修改上传模块 -->
    <div class="flexCenter" style="width: 100%; margin-top: 0.5rem;" v-if="operationName == '人脸样本'" >
      <img v-if="headImg == '' && imgDataSource.length <= 0" src="@/assets/img/default_head.png" class="headImgCss" alt="">
      <img v-if="headImg != '' && imgDataSource.length <= 0" :src="headImg" class="headImgCss" alt="">
      <img v-if="imgDataSource.length > 0" :src="imgDataSource[imgDataSource.length - 1]" class="headImgCss" alt="">
    </div>
    <button v-if="operationName == '人脸样本'" @click="uploadImg" class="buttonCss" style="width: 1.5rem; margin: 0.4rem 0 0 2.8rem;" >上传图片</button>
    <media ref="media" :showVoice='false' :showVideo='false' :showLink='false' style="display:none"></media>

    <!-- 两个功能的保存按钮 -->
    <div class="bigDivCss" >
      <x-button type="primary" v-if="operationName == '添加家长' || operationName == '编辑家长'"
      @click.native="preservationClick"
      style="width: 80%; background: #128fef;"
      >保存</x-button>

      <x-button type="primary" v-if="operationName == '人脸样本'"
      @click.native="preservationFace"
      style="width: 80%; background: #128fef;"
      >保存</x-button>
    </div>
  </div>
</template>

<script>
import headNav from '@/components/headNav/headNav.vue'
import { mapActions, mapState, mapGetters, mapMutations } from 'vuex'
import { XButton, Checklist, PopupHeader, Popup, Radio, Group } from 'vux'
import { getDictionariesApi, postTparentApi, putFaceApi } from '@/api/studentDetailsApi.js'
import {addFaceResource} from '@/api/faceApi' 
import media from '@/components/media'
import imgUtil from '@/util/imgUtil'
export default {
  components: {
    headNav,
    XButton,
    Checklist,
    PopupHeader,
    Popup,
    Radio,
    Group,
    media
  },
  computed: {
    ...mapState({
      studentId: state => state.user.studentId,
      schoolId: state => state.user.schoolId,
      imgDataSource () {
        return this.$store.state.media.imgDataSource
      },
      imgData () {
        return this.$store.state.media.imgData
      }
    })
  },
  data () {
    return {
      headImg: '',
      enumeration: [],
      relative: {  // 传过来的家长信息 （空代表是添加）
        id: '',
        name: '',
        phone: '',
        relationCode: ''
      },
      totalRelative: '',   // 登录用户的所有亲属
      operationName: '',   // 是什么功能跳转过来的
      show1: false,   // 亲属关系弹窗控制
      inputVal: ''
    }
  },
  methods: {
    // 添加编辑亲属保存按钮触发事件
    async preservationClick () {
      if (!this.relative.relationCode || !this.relative.name || !this.relative.phone) {
        this.$vux.toast.text('请完整填写家长信息', 'middle')
        console.log(this.totalRelative)
        return
      }
      if (this.operationName == '添加家长') {
        for (let item of this.totalRelative) {
          if (this.relative.phone == item.phone) {
            this.$vux.toast.text('该电话已经添加', 'middle')
            return
          }
        }
      }

      let list = []
      for (let i = 0; i < this.totalRelative.length; i++) {
        if (this.relative.phone.length > 11) {
          this.$vux.toast.text('电话号码格式不正确', 'middle')
          return
        }
        list.push({id: this.totalRelative[i].id,
                   name: this.totalRelative[i].name,
                   phone: this.totalRelative[i].phone,
                   relationCode: this.totalRelative[i].relationCode })
      }
      if (this.operationName == '添加家长') {
        list.push(this.relative)
      }
      if (this.operationName == '编辑家长') {
        for (let j = 0; j < list.length; j++) {
          if (this.relative.id == list[j].id ) {
            list[j].name = this.relative.name
            list[j].phone = this.relative.phone
            list[j].relationCode = this.relative.relationCode
          }
        }
      }
      this.parentDress(list)
    },
    // 上传图片按钮触发事件
    async uploadImg(){
      this.$store.dispatch('media/getFaceImg')
    },
    // 人脸样本保存按钮
    async preservationFace () {
      await this.$store.dispatch('media/upload')
      
      if(this.$store.state.media.imgData.length > 0) {
        this.headImg =  this.$store.state.media.imgData[this.$store.state.media.imgData.length - 1]
      }

      if(!this.headImg){
        this.$vux.toast.text('请上传图片', 'middle')
        return
      }
      
      let res = await imgUtil.checkImgForHuaWei(this.headImg)
      if(!res.flag){
        this.$vux.toast.text(res.msg, 'middle')
        return
      }

      this.face()
    },
    // 勾选亲属关系触发事件
    enumerationChange (e) {
      this.relative.relationCode = e
    },
    // 亲属弹窗确定按钮触发事件
    determineClick () {
      console.log(this.relative.relationCode)
      this.show1 = false
    },
    // 修改添加家长请求封装
    async parentDress (list) {
      let params = {
        id: JSON.parse(localStorage.detailsId).studentId,
        data: list
      }
      let res = await postTparentApi(params)
      this.$vux.toast.text('操作成功', 'middle')
      this.$router.push('details')
    },
    // 获取家长字典枚举封装
    async dictionaries () {
      let params = {
        typeCode: 'FamilyRelation'
      }
      let res = await getDictionariesApi(params)

      for (let i = 0; i < res.length; i++) {
        res[i].value = res[i].valName
        res[i].key = res[i].valCode
      }
      this.enumeration = res
    },
    // 修改人脸头像请求封装
    async face () {
      let params = {
        id: JSON.parse(localStorage.detailsId).studentId,
        data: {
          schoolId: this.schoolId,
          faceImgUrl: this.headImg
        }
      }
      // let res = await putFaceApi(params)

      let res = await this.addFaceResource()

      this.$vux.toast.text('操作成功', 'middle')
      // this.$router.push('details')
      this.$router.go(-1)
      console.log(res)


      
    },

     async addFaceResource () {
      

        // var student = JSON.parse(localStorage.detailsId)
        var student = JSON.parse(localStorage.headInformation)
        
        var person = {
          externalFields: {
            externalFields: {
                    schoolId: this.schoolId,
                    className: '',
                    personId: student.id,
                  
                    name: '',
                    faceImgUrl: '',
                    gender: student.gender ? 1 : 0,
                    personType: 1   // 教师：0，学生：1
            }
          },
          faceSetName: this.schoolId,
          personName: student.name,
          imageUrl: this.headImg,
           living: true
        }
      
        let res = await addFaceResource(person)

        if (res.status != 200) {
          this.$vux.alert.show({
              title: '错误',
              content: res.msg,
          })


          throw new Error(res.msg);
        } 
    },
    
  },
  async mounted() {
    this.dictionaries()
    if (localStorage.routerData) {
      this.operationName = localStorage.routerData
      localStorage.personalData == '' ? this.totalRelative = '' : this.totalRelative = JSON.parse(localStorage.personalData)
      if (this.operationName == '编辑家长') {
        this.relative =  JSON.parse(localStorage.relativeArr)
      }
    } else {
      this.$router.push('studentDetails')
    }
    JSON.parse(localStorage.headInformation).faceImgUrl ? this.headImg = JSON.parse(localStorage.headInformation).faceImgUrl : this.headImg = ''
    // console.log(JSON.parse(localStorage.relativeArr))
    
  }
 }
</script>

<style scoped lang="less" >
.headImgCss {
  max-width: 50%;
  margin-left: 1rem 0 0 1.75rem;
}

.buttonCss {
  width: 1rem;
  height: 0.5rem;
  border-radius: 0.15rem;
  background: #128fef;
  color: #FFF;
  border: 0;
  font-size: 0.23rem;
}

.bigDivCss {
  width: 100%;
  height: 1rem;
  font-size: 0.3rem;
  margin-top: 0.3rem;
  .flexAlign;
  span {
    margin-left: 0.3rem;
  }
  input {
    width: 4.5rem;
    height: 0.7rem;
    // color: #bfbfbf;
    font-size: 0.3rem;
    padding-left: 0.3rem;
  }
}
.flexAlign {
  display: flex;
  align-items: center;
}

.flexJustify {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.flexColumn {
  display: flex;
  flex-direction: column;
}

.flexCenter {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
<style>
.checklistCss .weui-cells {
  background: #F4F4F4;
}
</style>
